package hk.hku.hooku.servlet;

import hk.hku.hooku.db.UserDB;
import hk.hku.hooku.pojo.Contact;
import hk.hku.hooku.util.GoogleContactsAccess;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.util.ServiceException;

/**
 * Servlet implementation class ImportContactServlet
 */
public class ImportContactServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImportContactServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String userMail=request.getParameter("userMail");
		String address=request.getParameter("gmail");
		String password=request.getParameter("password");
		PrintWriter writer=response.getWriter();
		if(address!=null &&address!="" && password!=null && address!=""){
			try {
				ArrayList<Contact> contacts=GoogleContactsAccess.getGmailContacts(address, password);
				boolean isSuccessful=UserDB.addContacts(userMail, contacts);
				if(isSuccessful){
					writer.write("success");
					return;
				}
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
			}finally{
				writer.write("Import unsuccessful!");
				return;
			}
		}else{
			writer.write("Please complete the form.");
		}
	}

}
